package cn.wolfcode.shiro;

import cn.wolfcode.domain.Employee;
import cn.wolfcode.mapper.EmployeeMapper;
import cn.wolfcode.mapper.PermissionMapper;
import cn.wolfcode.mapper.RoleMapper;
import org.apache.shiro.authc.*;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.Objects;

/**
 * @author 杨兴健
 * @Date 2020/7/18 8:49
 */
public class CRMRealm extends AuthorizingRealm {

    private static final Logger log = LoggerFactory.getLogger(CRMRealm.class);

    @Autowired
    private EmployeeMapper mapper;
    @Autowired
    private PermissionMapper permissionMapper;
    @Autowired
    private RoleMapper roleMapper;

    /**
     * 重写凭证匹配器并注入我们写的凭证匹配器
     *
     * @param credentialsMatcher
     */
    @Override
    @Autowired
    public void setCredentialsMatcher(CredentialsMatcher credentialsMatcher) {
        super.setCredentialsMatcher(credentialsMatcher);
    }

    /**
     * 认证
     *
     * @param Token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken Token) throws AuthenticationException {
        //查询前端传来的用户
        Employee employee = mapper.selectByName((String) Token.getPrincipal());

        //判断用户是否存在
        if (Objects.nonNull(employee)) {
            //判断用户的状态
            if (!employee.isStatus()) {
                throw new DisabledAccountException("用户已禁用");
            }
            //把当前用户存进主体
            return new SimpleAuthenticationInfo(employee, employee.getPassword(), ByteSource.Util.bytes(employee.getName()), this.getName());
        }
        return null;
    }

    /**
     * 授权
     *
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        log.error("进入了doGetAuthorizationInfo");

        //获取员工
        Employee employee = (Employee) principalCollection.getPrimaryPrincipal();
        //创建授权信息对象
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

        if (employee.isAdmin()) {
            info.addRole("admin");
            info.addStringPermission("*:*");
        } else {
            //查询员工的全部权限
            List<String> permissions = permissionMapper.selectByEid(employee.getId());
            //查询员工的全部角色
            List<String> roles = roleMapper.selectSnByEid(employee.getId());
            //设置角色和权限到授权信息对象中
            info.addRoles(roles);
            info.addStringPermissions(permissions);
        }

        return info;
    }


}
